/* 
 * Copyright (c) 2019, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.boot.component.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import java.net.InetSocketAddress;
import javax.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * 服务启动协助类
 * @author xiongcong
 * @date 2019-07-24
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "netty", value = "port")
public class TCPServer {

    @Autowired
    @Qualifier("serverBootstrap")
    private ServerBootstrap serverBootstrap;

    @Autowired
    @Qualifier("tcpSocketAddress")
    private InetSocketAddress tcpPort;

    private Channel serverChannel;
    
    public void start() throws Exception {
        log.info("netty begin start， port : {}", tcpPort.getPort());
        serverChannel = serverBootstrap.bind(tcpPort).sync()
                .channel().closeFuture().sync().channel();
    }

    @PreDestroy
    public void stop() throws Exception {
        serverChannel.close();
        serverChannel.parent().close();
    }
}
